package org.lundberg.podcasts.util;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.lundberg.podcasts.R;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class QueueAdapter extends CursorAdapter
{
	public static final String[] COLUMNS = new String[] {"guid",
														"channel_id",
														"title",
														"pubDate",
														"size",
														"_id"};
	private HashMap<Integer, Bitmap> iconCache;
	private HashMap<Integer, ArrayList<ImageView>> iconQueue;
	private Context ctx;
	
	public QueueAdapter (Context context, Cursor c, HashMap<Integer, Bitmap> iconCache) {
		super(context, c, false);
		this.ctx = context;
		this.iconCache = iconCache;
		iconQueue = new HashMap<Integer, ArrayList<ImageView>>();
	}
	
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent)
	{	
		final LayoutInflater inflater = LayoutInflater.from(context);
		return inflater.inflate(R.layout.queue_row, parent, false);
	}
	
	
	@Override
	public void bindView(View view, Context context, Cursor c)
	{
		final ImageView icon = (ImageView)view.findViewById(R.id.icon);
		
    	if (iconCache.containsKey(c.getInt(1))) {

    		Bitmap bm = iconCache.get(c.getInt(1));
    		if (bm != null) {
    			icon.setImageBitmap(bm);
    		}
    		else {
    			icon.setImageResource(R.drawable.default_thumbnail);
    		}
    	}
    	else {
    		
    		icon.setImageResource(R.drawable.default_thumbnail);
    		
    		ArrayList<ImageView> list = iconQueue.get(c.getInt(1));
    		
    		if (list == null) {
    			list = new ArrayList<ImageView>();
    			final int channel_id = c.getInt(1);
    			
    			ViewTreeObserver vto = icon.getViewTreeObserver();
    			vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    			    public boolean onPreDraw() {
    			    	new QueueAdapterDownloadIconTask(ctx, channel_id, icon.getWidth(), icon.getHeight()).execute();
    			    	icon.getViewTreeObserver().removeOnPreDrawListener(this);
    			        return true;
    			    }
    			});
    			
    		}
    		
    		list.add(icon);
    		iconQueue.put(c.getInt(1), list);
    		
    	}
		
		
		TextView title = (TextView) view.findViewById(R.id.title);
		title.setText(c.getString(2));            
        
		TextView date = (TextView)view.findViewById(R.id.date);
        date.setText(Util.getItemAge(c.getString(3)));
        
        float fileSize = 0.0f;
        
        TextView size = (TextView)view.findViewById(R.id.size);
        
        boolean downloaded = Util.isDownloaded(c.getString(0));
        
        if (downloaded) {

        	fileSize = (c.getInt(4) > 0) ? toMegabytes(c.getInt(4)) : getFileSize(c.getString(0));
        	size.setTextColor(context.getResources().getColor(R.color.gray));
        }
        else {
        	
        	size.setTextColor(context.getResources().getColor(R.color.dark_gray));
        }
        
        size.setText(String.format(context.getResources().getString(R.string.size), fileSize));
	}
	
	
	
	
	private static float getFileSize(String guid)
	{
		File file = new File(Util.getPodcastFilename(guid));
		long length = file.length();
		
		if (length == 0) {
			file = new File(file.getAbsolutePath()+".tmp");
			length = file.length();
		}
		
		return toMegabytes(length);
	}
	
	
	
	private static float toMegabytes(long size)
	{
		return (size > 0) ? (size / 1048576.0f - 0.05f) : 0.0f;
	}
	
	
	
	private class QueueAdapterDownloadIconTask extends DownloadIconTask
    {
    	private int channel_id;
    	private WeakReference<Context> activity;
    	
    	public QueueAdapterDownloadIconTask(Context activity, int channel_id, int viewWidth, int viewHeight) {
    		
    		super(PodcastDB.getImageURL(activity, channel_id), viewWidth, viewHeight);
    		
    		this.channel_id = channel_id;
    		this.activity = new WeakReference<Context>(activity);
    	}
    	
    	@Override
    	public void onPreExecute() {
    		
    		networkAvailable = Util.isNetworkAvailable(activity.get());
    	}
    	
    	@Override
    	protected void onPostExecute(Bitmap bitmap)
    	{    		
    		if (bitmap != null)
    		{
				iconCache.put(channel_id, bitmap);
				ArrayList<ImageView> list = iconQueue.get(channel_id);
				if (list != null)
				{
					for (Iterator<ImageView> it = list.iterator(); it.hasNext();) {
						
						ImageView v = it.next();
						
						TransitionDrawable d = new TransitionDrawable(
								new Drawable[] {v.getDrawable(), new BitmapDrawable(activity.get().getResources(), bitmap)});
						v.setImageDrawable(d);
						d.setCrossFadeEnabled(true);
						d.startTransition(500);
						
						it.remove();
					}
				}
				
				// remove the queue for this channel
				iconQueue.remove(channel_id);
				
    		}
    	}
    }

}
